package com.hcrazy.manchester.app.services;

import java.util.List;

import org.springframework.util.StringUtils;

import com.hcrazy.manchester.app.jdbc.FoodTypeDAO;
import com.hcrazy.manchester.app.jdbc.SellerDAO;
import com.hcrazy.manchester.app.pojo.ErrorMsg;
import com.hcrazy.manchester.app.pojo.FoodType;
import com.hcrazy.manchester.app.pojo.PageModel;
import com.hcrazy.manchester.app.pojo.Seller;
import com.hcrazy.manchester.app.utils.Constant;

public class SellerService {

	private SellerDAO sellerDAO;
	
	private FoodTypeDAO foodTypeDAO;
	
	public FoodTypeDAO getFoodTypeDAO() {
		return foodTypeDAO;
	}

	public void setFoodTypeDAO(FoodTypeDAO foodTypeDAO) {
		this.foodTypeDAO = foodTypeDAO;
	}

	public SellerDAO getSellerDAO() {
		return sellerDAO;
	}

	public void setSellerDAO(SellerDAO sellerDAO) {
		this.sellerDAO = sellerDAO;
	}

	public ErrorMsg addOrUpdateSeller(Seller seller) throws Exception{
		ErrorMsg msg = new ErrorMsg();
		msg.setCode(Constant.SUCCESS);//success
		
		if(seller.getSellerId() > 0){
			sellerDAO.updateSeller(seller);
		}else{
			sellerDAO.addSeller(seller);
		}
		
		return msg;
	}
	
	public PageModel getSellers(PageModel model,String search,int foodType,long userId) throws Exception{
		PageModel pm = sellerDAO.getPagedSellers(model, search, foodType,userId);
		if(null != pm && null != pm.getResult() && !pm.getResult().isEmpty()){
			List<FoodType> fts = foodTypeDAO.getList();
			for(Object obj : pm.getResult()){
				Seller seller = (Seller)obj;
				String types = seller.getFoodType();
				if(null != types){
					String[] ts = types.split(",");
					String[] names = new String[ts.length];
					for(int i=0;i<ts.length;i++){
						String id = ts[i];
						int typeId = Integer.parseInt(id);
						for(FoodType ft:fts){
							if(typeId == ft.getTypeId()){
								names[i] = ft.getTypeName();
								break;
							}
						}
					}
					
					seller.setFoodTypeName(StringUtils.arrayToCommaDelimitedString(names));
				}
			}
		}
		return pm;
	}
	
	public Seller getSellerById(long sellerId) throws Exception{
		return sellerDAO.getById(sellerId);
	}
	
	public void delSeller(long sellerId) throws Exception{
		sellerDAO.delSeller(sellerId);
	}
	
	public List<Seller> getAllSellers() throws Exception{
		return sellerDAO.listAllInfos();
	}
	
	public List<Seller> getSellersByUserId(long userId) throws Exception{
		return sellerDAO.listAllInfos(userId);
	}
}
